extends CharacterBody2D

@export var move_speed: float = 50.0
@export var detection_range: float = 150.0
@export var attack_damage: int = 15
@export var attack_cooldown: float = 1.0
@export var attack_range: float = 40.0  # 攻击范围

## 血量设置
@export var max_health: int = 50
@export var current_health: int

var player: Node2D = null
var start_position: Vector2
var patrol_target: Vector2
var is_chasing: bool = false
var last_attack_time: float = 0.0

func _ready():
	# 初始化血量
	current_health = max_health
	
	start_position = global_position
	set_new_patrol_target()
	
	# 查找玩家
	player = get_tree().get_first_node_in_group("player")

func _physics_process(delta):
	if player:
		var distance_to_player = global_position.distance_to(player.global_position)
		
		if distance_to_player <= detection_range:
			# 追击玩家 - 一直移动，不停止
			is_chasing = true
			move_towards(player.global_position)
			
			# 检查是否可以攻击玩家（直接碰撞检测）
			if distance_to_player <= 20 and can_attack_player():  # 20像素内算碰撞
				attack_player()
		else:
			# 巡逻
			is_chasing = false
			handle_patrol(delta)
	else:
		# 没有玩家时巡逻
		handle_patrol(delta)

func handle_patrol(_delta):
	if global_position.distance_to(patrol_target) < 20:
		set_new_patrol_target()
	else:
		move_towards(patrol_target)

func move_towards(target: Vector2):
	var direction = (target - global_position).normalized()
	velocity = direction * move_speed
	move_and_slide()

func set_new_patrol_target():
	var random_angle = randf() * TAU
	patrol_target = start_position + Vector2(
		cos(random_angle) * 100,
		sin(random_angle) * 100
	)

func take_damage(damage: int):
	current_health -= damage
	current_health = max(0, current_health)
	print("敌人受到伤害: ", damage, " 当前血量: ", current_health)
	
	# 如果血量耗尽，死亡
	if current_health <= 0:
		die()

func die():
	print("敌人死亡！")
	# 播放死亡动画或效果
	queue_free()  # 从场景中移除敌人

func can_attack_player() -> bool:
	var current_time = Time.get_ticks_msec()
	return current_time >= last_attack_time + attack_cooldown * 1000

func attack_player():
	if player and player.has_method("take_damage"):
		player.take_damage(attack_damage)
		last_attack_time = Time.get_ticks_msec()
		print("敌人攻击玩家，造成伤害: ", attack_damage)
	else:
		print("敌人无法攻击玩家")

## 获取敌人当前速度（用于预判）
func get_enemy_velocity() -> Vector2:
	return velocity
